package pri.damai.xiaowu.auth.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * MVC 配置
 *
 * @Desc 1.主要用于返回值统一包装时的序列化处理。
 * 2.继承了WebMvcConfigurationSupport，则在yml中配置的静态资源相关内容会失效。需要重新指定静态资源。
 * @Author DaMai
 * @Date 2021/3/23 15:06
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Value("${spring.jackson.date-format}")
    private String pattern;


    /**
     * 配置 MVC 的 HTTP消息转化
     *
     * @param converters
     * @return void
     * @apiNote 把 StringOrMappingJackson2HttpMessageConverter 设置在第一位
     * @author DaMai
     * @date 2021/3/23 15:06
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        StringOrMappingJackson2HttpMessageConverter converter = new StringOrMappingJackson2HttpMessageConverter();

        this.addObjectMapperFor(converter);

        converters.add(0, converter);

        super.extendMessageConverters(converters);
    }

    /**
     * HTTP 序列化
     *
     * @Desc 兼容处理处理返回值是String的情况
     * @Author DaMai
     * @Date 2021/3/23 15:06
     */
    public static class StringOrMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {

        private static final StringHttpMessageConverter SHMC = new StringHttpMessageConverter();

        @Override
        public boolean canWrite(Class<?> clazz, MediaType mediaType) {

            boolean canWrite = super.canWrite(mediaType);

            if (!canWrite) {
                // 判断类继承
                canWrite = clazz.isAssignableFrom(String.class);
            }

            return canWrite;
        }

        @Override
        protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {

            if (object instanceof String) {
                outputMessage.getHeaders().setContentType(MediaType.TEXT_PLAIN);
                SHMC.write((String) object, MediaType.TEXT_PLAIN, outputMessage);
                return;
            }
            outputMessage.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            super.writeInternal(object, object.getClass(), outputMessage);
        }
    }

    /**
     * JackSon序列化的相关配置
     *
     * @param converter
     * @apiNote [描述此方法]
     * @author DaMai
     * @date 2021/3/23 15:06
     */
    public void addObjectMapperFor(StringOrMappingJackson2HttpMessageConverter converter) {

        ObjectMapper objectMapper = new ObjectMapper();

        // 空对象不报错
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);

        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // LocalDataTime 的序列化和反序列化
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(pattern)));

        objectMapper.registerModule(javaTimeModule);
        converter.setObjectMapper(objectMapper);
    }

    /**
     * 指定静态资源路径
     *
     * @param registry
     * @apiNote 发现如果继承了WebMvcConfigurationSupport，则在yml中配置的相关内容会失效。需要重新指定静态资源
     * @author DaMai
     * @date 2021/3/23 15:06
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        registry.
                addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
        super.addResourceHandlers(registry);
    }

    /**
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //放开的登录拦截
//        registry.addInterceptor(adminInterceptor).addPathPatterns("/**")
//                .excludePathPatterns("/swagger**/**", "/webjars/**", "/v3/**", "/doc.html");
    }



    /**
     * RequestContextListener监听器,处理获取请求上下上下文为空的问题
     * @return
     */
    @Bean
    public RequestContextListener requestContextListenerBean() {
        return new RequestContextListener();
    }
}
